﻿using System;
using System.Collections.Generic;
using System.Text;
namespace HCService.MsgHandler
{
	public sealed class Pack
	{
		byte[] buffer;
		int curIndex = 0;
		string handleTag = "";
		byte[] packBuffer;

		public byte[] Buffer { get => buffer; set => buffer = value; }
		public int CurIndex { get => curIndex; set => curIndex = value; }
		public string HandleTag { get => handleTag; set => handleTag = value; }
		public byte[] PackBuffer { get => packBuffer; set => packBuffer = value; }
		public int ResumeSize => buffer.Length - CurIndex;

		public Pack(int size)
		{
			if (size <= 0 || size > int.MaxValue)
				throw new Exception("Invail Array Length");
			else	
				this.buffer = new byte[size];
		}

		/*
		public void ReadBuffer(int length)
		{
			//每次读取一定长度的数据
			this.curIndex += length;
			if(curIndex <= 4) return;
			int count = BitConverter.ToInt32(buffer, 0);
			//可用头部信息
			while (true)
			{
				//从头部读取长度
				var packsize = count + sizeof(Int32);
				//等待接受数据完整
				if (curIndex >= packsize)
				{
					//ProtoPack pack = ProtoPack.Descriptor.Parser.ParseFrom(
					//		buffer, sizeof(Int32), count) as ProtoPack;
					packBuffer = new byte[count];
					//提取包信息
					Array.Copy(buffer, sizeof(Int32), packBuffer, 0, count);

					//将当前完整Pack移除buffer
					Array.Copy(buffer, packsize, buffer, 0, curIndex - packsize);
					curIndex -= packsize;
				}
				else 
				{
					//不满足头部长度则结束
					break;
				}
			}
		}
		*/
		public override string ToString()
		{
			return $"HandleTag : {Encoding.UTF8.GetString(Buffer)}";
		}
		public string ToStringBuff()
		{
			return Encoding.UTF8.GetString(PackBuffer);
		}
		public bool Build()
		{
			PackBuffer = null;
			//当前包不完整
			if (curIndex != Buffer.Length)
				return false;
			//  tag length || tag || content
			// 当前包体至少是 sizeof(Int32) + tagLength 长度
			if (Buffer.Length < sizeof(Int32)) return false;
			int tagLength = BitConverter.ToInt32(Buffer, 0);
			if (Buffer.Length < sizeof(Int32) + tagLength) return false;
			string tagName = Encoding.UTF8.GetString(Buffer, sizeof(Int32), tagLength);

			int contentSize = Buffer.Length - sizeof(Int32) - tagLength;
			//内容长度出现异常
			if (contentSize < 0)
				return false;
			PackBuffer = new byte[contentSize];
			Array.Copy(Buffer, sizeof(Int32) + tagLength, PackBuffer, 0, contentSize);

			HandleTag = tagName;
			return true;
		}
	}
}
